package com.teamin.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teamin.config.ErrorCode;
import com.teamin.entity.UserEntity;
import com.teamin.entity.WxUserEntity;
import com.teamin.service.JwtService;
import com.teamin.service.UserService;
import com.teamin.service.WxService;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import com.teamin.web.model.JwtInfo;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 登陆接口，不需要token验证的接口
 *
 * @author 31484
 *
 */
@RestController
@Api(description = "用户登录接口",tags = "登录")
public class LoginController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	PodamFactory factory = new PodamFactoryImpl();
	@Autowired
	private JwtService jwtService;
	@Autowired
	private UserService userService;

	@Autowired
	private WxService wxService;

	/**
	 *
	 * @param code 微信登录中取到的code 用于获取用户的信息
	 * @param encryptedData 加密后的用户数据
	 * @param iv 密匙
	 * @return UserEntity 用户基本信息
	 * @throws GlobalErrorInfoException
	 */
	@RequestMapping(value = "/v1/login", method = RequestMethod.POST)
	public JSONObject login(@RequestParam(required = true) String code,
			@RequestParam(required = true) String encryptedData, @RequestParam(required = true) String iv)
			throws GlobalErrorInfoException {
		logger.info("login = "+ encryptedData + "  "+iv);

		//解密并获取微信用户的基本信息
		WxUserEntity wxUserEntity = wxService.getWxUserEntity(code, encryptedData, iv);

		//获取用户的基本信息
		UserEntity userEntity = userService.wxLogin(wxUserEntity);

		// 将登陆用户添加到token中
		HashMap<String, Long> map = new HashMap<String, Long>();
		map.put("userId", userEntity.getUserId());

		// FIXME token 后台应该存一份,如果有户有异常登录可以直接在服务器端关闭此token,并且如果调用刷新token后此token还会有效
		JwtInfo token = jwtService.getTokenInfo(map);

		// 用户类转jsonobject
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(userEntity));

		if(userService.getLoginTime(userEntity.getUserId()) == null) {
			jsonObject.put("existUser",false) ;
		}else {
			jsonObject.put("existUser",true) ;
		}

		// 添加jwt信息
		jsonObject.put("jwtInfo", token);
		return jsonObject;
	}

	/**
	 *
	 */
	@RequestMapping(value = "/v1/pcLogin", method = RequestMethod.POST)
	public JSONObject pcLogin(@RequestParam(required = true) String code,
			@RequestParam(required = true) String state)
					throws GlobalErrorInfoException {
		logger.info("pcLogin = "+ code + "  " + state);
		//解密并获取用户的基本信息
		UserEntity userEntity = userService.wxPcLogin(code, state);

		// 将登陆用户添加到token中
		HashMap<String, Long> map = new HashMap<String, Long>();
		map.put("userId", userEntity.getUserId());

		// FIXME token 后台应该存一份,如果有户有异常登录可以直接在服务器端关闭此token,并且如果调用刷新token后此token还会有效
		JwtInfo token = jwtService.getTokenInfo(map);

		// 用户类转jsonobject
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(userEntity));

		// 添加jwt信息
		jsonObject.put("jwtInfo", token);

		if(userService.getLoginTime(userEntity.getUserId()) == null) {
			jsonObject.put("existUser",false) ;
		}else {
			jsonObject.put("existUser",true) ;
		}

		return jsonObject;
	}

	/**
	 * 刷新token
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/v1/token", method = RequestMethod.GET)
	public JSONObject refreshToken(HttpServletRequest request) {
		String token = jwtService.getToken(request.getAttribute("loginInfo"));
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token", token);
		return jsonObject;
	}

	/**
	 * 处理/error页面
	 *
	 * @return
	 * @throws GlobalErrorInfoException
	 * @throws Exception
	 */
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public void error(HttpServletRequest request, HttpServletResponse response) throws GlobalErrorInfoException {
		int status = response.getStatus();
		if (status == 404) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.NOT_FOUND));
		} else {
			logger.warn("/error 出现未知错误 ：" + status);
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.valueOf(status), ErrorCode.UNKNOWN_ERROR));
		}
	}

}